import { EcgData } from "@/pages/types/type"

export function parseFilter(filter : number) : string {
	let info = ''
	if ((filter & 1) === 1) info = 'HUM'
	if (((filter >> 1) & 1) === 1) info = info + ' EMG'
	if (((filter >> 2) & 1) === 1) info = info + ' EMG25'
	if (((filter >> 3) & 1) === 1) info = info + ' ADS'

	info.trim
	//String.replaceAll.apply(null,info,' ','/')
	info.replace(' ', '/')
	return info
}

export function decodeWaveFromHexStr(hex : string) {
	if (hex.length % 2 !== 0) throw new Error('无效的hex字符串');
	let byteLength = hex.length / 2;
	const zlibArray = new Uint8Array(byteLength)
	for (let i = 0; i < byteLength; i++) {
		zlibArray[i] = parseInt(hex.substring(i * 2, i * 2+2), 16);
	}

	// const unpackU8Array = pako.inflate(zlibArray)
	return decodeWaveFromArrayBuffer(zlibArray.buffer);
}

export function decodeWaveFromArrayBuffer(ab : ArrayBuffer) : EcgData {
	let wave : EcgData = {
		/** 文件标志 */
		tag: '',
		/** 水平分辨率 点/秒*/
		resH: 1000,
		/** 垂直分辨率 点/mv*/
		resV: 200,
		/** 滤波器信息 */
		filter: '',
		/** 心电类型
		 * 0=VECG : I II III X Y Z
		 * 1=ECG12 : 12
		 * 2=ECG15 : 12 + V7 V8 V9
		 * 3=ECG18 : 12 + V7 V8 V9 V3R V4R V5R
		 * 4=Atropin : II
		 */
		ecgType: 0,
		/** 实际导联名称 */
		leadNames: [],
		/** 导联数 */
		leadCount: 12,
		/** 姓名/心电图号/医院名称 */
		patInfo: [],
		/** 性别
		 * 1=男
		 * 2=女
		 */
		sex: 0,
		/** 年龄值   */
		ageValue: 0,
		/** 年龄单位 */
		ageUnit: '',
		data: {},
		/** 单通道数据长度 */
		dataLength: 0,
	}

	console.log('start decode ecg buffer');

	//初始化
	if (ab.byteLength < 592) throw new Error('解析失败,数据头错误')


	const header = new DataView(ab, 0, 592)
	let offset = 0

	// tag
	wave.tag = String.fromCharCode.apply(null, Array.from(new Uint8Array(ab.slice(offset,
		4)))); //enc.decode(ab.slice(offset, 4))
	console.log(wave.tag);
	if (wave.tag !== '3RAY') throw new Error('解析失败')
	offset += 4

	wave.resH = header.getInt16(offset, true)
	offset += 2
	wave.resV = header.getInt16(offset, true)
	offset += 2
	wave.filter = parseFilter(header.getUint8(offset))
	offset++
	wave.ecgType = header.getUint8(offset)
	offset++

	offset += 8 // reserved

	offset++

	let str = String.fromCharCode.apply(null,
		Array.from(new Uint8Array(ab.slice(offset, offset + 60)))); //enc.decode(ab.slice(offset, 60))

	str = str.substring(0, str.lastIndexOf(';'))
	wave.leadNames = str.split(';')
	wave.leadNames = wave.leadNames.filter(name => {
		return name.length > 0
	})
	wave.leadCount = wave.leadNames.length

	offset += 60


	offset++

	str = String.fromCharCode.apply(null,
		Array.from(new Uint8Array(ab.slice(offset, offset + 61)))); //enc.decode(ab.slice(offset, 61))
	str = str.substring(0, str.lastIndexOf('@'))
	wave.patInfo = str.split('@')
	offset += 61

	offset++

	offset += 133

	wave.sex = header.getUint8(offset)

	offset++

	wave.ageValue = header.getUint8(offset)
	offset++
	const age = header.getUint8(offset)

	wave.ageUnit = '岁'
	if (age === 1) wave.ageUnit = '月'
	if (age === 2) wave.ageUnit = '天'

	// header===============================================
	wave.leadNames.forEach(val => {
		wave.data[val] = []
	})

	// decode data=========================================
	const dv = new DataView(ab, 592, ab.byteLength - 592)

	offset = 0
	let tag = 0
	let k = 0
	let points = 0
	let packLen = 0
	let key = ''
	let ax = 0
	for (let i = 0; i < dv.byteLength;) {
		tag = dv.getUint8(i)
		points = dv.getUint8(i + 1)
		if (tag === 0) {
			packLen = 4 + (points - 1) * 2
		} else {
			packLen = 4 + points - 1
		}

		ax = dv.getInt16(i + 2, true)
		key = wave.leadNames[k]
		if (tag === 0) {
			// 原始数据
			wave.data[key].push(ax)
			for (let j = 1; j < points; j++) {
				wave.data[key].push(dv.getInt16(i + 2 + 2 * j, true))
			}
		} else if (tag === 1) {
			// 差分数据
			wave.data[key].push(ax)
			for (let j = 1; j < points; j++) {
				ax = ax + dv.getInt8(i + 3 + j)
				wave.data[key].push(ax)
			}
		}

		i += packLen
		k++

		if (k === wave.leadCount) {
			k = 0
			wave.dataLength += points
		}
		// console.log(key, ':')
	}

	return wave
}